import storage from '../../utils/storage'
import router from '../../router'

export default {
  state: {
    // tags: storage.getOrInsert('navbar_tags', [])
    tags: [
      {
        name: 'Home',
        path: '/',
        closable: false
      }
    ]
  },
  mutations: {
    /**
     * Add a tag
     * @param {any} state state instance
     * @param {object} args tag options
     * @param {string} args.name tag name
     * @param {string} args.path nav path
     */
    addTag(state, { name, path }) {
      if (!state.tags.some((t) => t.path === path)) {
        state.tags = [
          ...state.tags,
          {
            name,
            path,
            closable: true
          }
        ]
      }
    },
    delTag(state, path) {
      const targetIdx = state.tags.findIndex((t) => t.path === path)
      const currentIdx = state.tags.findIndex((t) => t.path === router.currentRoute.path)

      if (targetIdx !== -1) {
        state.tags.splice(targetIdx, 1)

        currentIdx === targetIdx && router.push(state.tags[targetIdx - 1].path)
      }
    },
    delOtherTag(state, path) {
      state.tags = state.tags.filter((t) => t.path === path || t.path === '/')
      router.currentRoute.path !== '/' && router.push(path)
    }
  }
}
